// @ts-nocheck
import { defineStore } from "pinia";
import * as RongIMLib from "@rongcloud/imlib-next";
import {loginApi} from "@/api";
import tips from "@/utils/tips";

export const rongCloudStore:any = defineStore({
    id: 'rongCloud',
    unistorage: true, // 开启后对 state 的数据读写都将持久化
    // 推荐使用 完整类型推断的箭头函数
    state: () => {
        return {
            appkey:'pvxdm17jpho4r',
            CONNECTED: false, // 是否连接
            conversationList: [], // 会话列表
        }
    },
    actions: {
        init(){
            // 应用初始化以获取 RongIMLib 实例对象，请务必保证此过程只被执行一次
            RongIMLib.init({appkey: this.appkey});
            // 添加事件监听
            const Events = RongIMLib.Events

            RongIMLib.addEventListener(Events.CONNECTING, () => {
                console.log('正在链接服务器')
            })

            RongIMLib.addEventListener(Events.CONNECTED, () => {
                console.log('已经链接到服务器')
                this.CONNECTED = true
                this.getMessageList()
            })

            RongIMLib.addEventListener(Events.MESSAGES, (evt) => {
                console.log('收到消息', evt.messages)
                uni.$emit('receiveMessage', evt.messages[0])
            })

            RongIMLib.addEventListener(Events.CONVERSATION, (evt) => {
                console.log('会话更新',evt.conversationList)
                uni.$emit('updataConversation', evt.conversationList)
            })
            this.connectSocket()

        },

        // 连接融云
        connectSocket() {
            let rc_token = uni.getStorageSync('rc_token')
            RongIMLib.connect(rc_token).then(res => {
                console.log(res)
                if (res.code === RongIMLib.ErrorCode.SUCCESS) {
                    tips.showToast('连接成功')
                    console.log('链接成功, 链接用户 id 为: ', res.data.userId);
                } else {
                    console.warn('链接失败, code:', res.code)
                }
            })
        },
        // 断开连接
        disconnect(){
            RongIMLib.disconnect().then(() => {
                console.log('成功断开')
            })
        },

        // 获取会话列表
        getMessageList(){
            RongIMLib.getConversationList().then(({ code, data: conversationList }) => {
                if (code === 0) {
                    this.sessionList(conversationList)
                } else {
                    console.log('获取会话列表失败: ', code,conversationList);
                    uni.switchTab({
                        url: '/pages/login/login'
                    })
                }
            });
        },
        // 获取会话信息
        async sessionList (conversationList:any){
            let ids = conversationList.map((item:any)=>item.targetId || item.conversation.targetId).join(',')
            let res = await loginApi.getUserInfoByIds({ids})
            let list = conversationList.reduce((prev: any[], cur: any) => {
                let itemValue = {};
                if (cur.conversation) {
                    itemValue = res.data.find(item => item.id == cur.conversation.targetId) || {};
                } else {
                    itemValue = res.data.find(item => item.id == cur.targetId) || {};
                }
                const baseObject = cur.conversation ? { ...cur.conversation } : { ...cur };
                const mergedObject = {
                    ...baseObject,
                    userInfo: itemValue,
                    show: false
                };
                prev.push(mergedObject);
                return prev;
            }, []); // 初始值是一个空数组
            // console.log('this.conversationList',this.conversationList)
            console.log('list',list)
            console.log('获取会话列表成功', this.conversationList);
            // this.conversationList = []
            list.map((item:any,index:number)=>{
                let ind = this.conversationList.findIndex(i=>i.targetId === item.targetId)
                if(ind !== -1){
                    console.log('相同会话',ind)
                    this.conversationList.splice(ind,1,item)
                }else{
                    console.log('不相同会话',item)
                    this.conversationList.push(item)
                }
            })
            // this.conversationList = add ? this.conversationList.concat(list) : list
            console.log('list',list)
            console.log('获取会话列表成功', this.conversationList);
        },
        // 删除会话
        removeSession(targetId:string){
            console.log('删除会话Id',targetId)
            RongIMLib.removeConversation({
                conversationType:RongIMLib.ConversationType.PRIVATE,
                targetId: targetId,
            }).then(res => {
                // 删除指定会话成功
                if(res.code === 0){
                    console.log(res.code)
                    this.conversationList = this.conversationList.filter(item=>item.targetId !== targetId)
                } else {
                    console.log(res.code, res.msg)
                }
            })
        },
        // 置顶会话
        topSession(item:any){
            console.log('置顶会话Id',item.targetId)
            RongIMLib.setConversationToTop({
                conversationType:RongIMLib.ConversationType.PRIVATE,
                targetId:item.targetId,
            }, item.isTop).then(({code}) => {
                // 设置会话置顶成功
                if( !code ){
                    let index = this.conversationList.findIndex(value=>value.targetId === targetId)
                    this.conversationList[index].show = false
                    this.conversationList.splice(index,1)
                    // this.conversationList.unshift(value)
                    // console.log(this.conversationList)
                }
            })
        }
    },
})